package controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pojo.User;
import service.UserService;

import java.util.List;
import java.util.Map;

@Controller()
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;



    @RequestMapping("test")
    public String toTest(){
        return "test";
    }

    @PostMapping("queryUser")
    @ResponseBody
    public User queryUser(@RequestBody User user){
        return userService.queryByPhone(user.getPhone());
    }


    @PostMapping("getAllUser")
    @ResponseBody
    public List<User> getAllUser(){
        return userService.queryAllUser();
    }


    @PostMapping("login")
    @ResponseBody
    public User login(@RequestBody User user){
        return userService.login(user.getPhone(),user.getPassword());
    }

    @PostMapping("addUser")
    @ResponseBody
    public int addUser(@RequestBody User user){
        return userService.addUser(user);
    }

    @PostMapping("updateUser")
    @ResponseBody
    public int updateUser(@RequestBody Map<String, Object> map) throws JsonProcessingException {
        String oldPhone = (String) map.get("oldPhone");
        //map转对象
        ObjectMapper mapper = new ObjectMapper(); //转换器
        User user=mapper.readValue( mapper.writeValueAsString(map.get("user")), User.class);
        return userService.updateUser(user,oldPhone);
    }
}
